package network

import (
	"io/ioutil"
	"net/http"
	"strings"
	"time"
	"zcommom/zlog"
)

//超时请求 url:地址，params map参数  time:超时时间
func Hget(url string, params map[string]interface{}, _time int) (body string, err error) {
	__times := time.Second * 1 * time.Duration(_time)
	client := http.Client{Timeout: __times}
	paramStr := ""
	if params != nil {
		paramStr = "?"
		i := 0
		for index, param := range params {
			i++
			if i < len(params) {
				paramStr += index + "=" + param.(string) + "&"
			} else {
				paramStr += index + "=" + param.(string)
			}

		}
	}

	resp, err := client.Get(url + paramStr)

	if err != nil {
		zlog.Info("Hget", err)
		return "", err
	}

	defer resp.Body.Close()
	ret, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		zlog.Info("Hget1", err)
		return "", err
	}
	body = string(ret)
	zlog.Info("Hget body", body)
	return string(body), err
}

//发送post请求，默认5秒
func Hpost(_url string, param map[string]string, _times int) (result string, err error) {
	__times := time.Second * 1 * time.Duration(_times)
	client := http.Client{Timeout: __times}
	str := ""
	if param != nil {
		for k, val := range param {
			if str == "" {
				str = k + "=" + val
			} else {
				str = str + "&" + k + "=" + val
			}
		}
	}

	resp, err := client.Post(
		_url,
		"application/x-www-form-urlencoded",
		strings.NewReader(str))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	result = string(body)
	return result, err
}

//发送json
func Hjson(_url string, param string, _times int) (result string, err error) {
	__times := time.Second * 1 * time.Duration(_times)

	client := http.Client{Timeout: __times}

	resp, err := client.Post(
		_url,
		"application/json",
		strings.NewReader(param))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	result = string(body)
	return result, err
}
